package main

import (
	"fmt"
	"regexp"
	"strings"
)

var (
	PREFIX_GP = false
	PREFIX_PG = false
)

var GlobalMap = map[string]string{
	"qb_catalog":                         "pg_catalog",
	"qb_class":                           "pg_class",
	"qb_namespace":                       "pg_namespace",
	"qb_stat_activity":                   "pg_stat_activity",
	"qb_export_snapshot":                 "pg_export_snapshot",
	"qb_settings":                        "pg_settings",
	"qb_authid":                          "pg_authid",
	"qb_size_pretty":                     "pg_size_pretty",
	"qb_depend":                          "pg_depend",
	"qb_attribute":                       "pg_attribute",
	"qb_attrdef":                         "pg_attrdef",
	"qb_description":                     "pg_description",
	"qb_collation":                       "pg_collation",
	"qb_seclabel":                        "pg_seclabel",
	"qb_get_expr":                        "pg_get_expr",
	"qb_options_to_table":                "pg_options_to_table",
	"qb_get_table_distributedby":         "pg_get_table_distributedby",
	"qb_exttable":                        "pg_exttable",
	"qb_foreign_table":                   "pg_foreign_table",
	"qb_encoding_to_char":                "pg_encoding_to_char",
	"qb_partitioned_table":               "pg_partitioned_table",
	"qb_partition_root":                  "pg_partition_root",
	"qb_am":                              "pg_am",
	"qb_foreign_server":                  "pg_foreign_server",
	"qb_inherits":                        "pg_inherits",
	"qb_get_partkeydef":                  "pg_get_partkeydef",
	"qb_resqueue":                        "pg_resqueue",
	"qb_shdescription":                   "pg_shdescription",
	"qb_resgroup":                        "pg_resgroup",
	"qb_auth_time_constraint":            "pg_auth_time_constraint",
	"qb_shseclabel":                      "pg_shseclabel",
	"qb_auth_members":                    "pg_auth_members",
	"qb_get_userbyid":                    "pg_get_userbyid",
	"qb_db_role_setting":                 "pg_db_role_setting",
	"qb_roles":                           "pg_roles",
	"qb_proc":                            "pg_proc",
	"qb_language":                        "pg_language",
	"qb_get_function_arguments":          "pg_get_function_arguments",
	"qb_get_function_identity_arguments": "pg_get_function_identity_arguments",
	"qb_get_function_result":             "pg_get_function_result",
	"qb_extprotocol":                     "pg_extprotocol",
	"qb_extension":                       "pg_extension",
	"qb_range":                           "pg_range",
	"qb_opclass":                         "pg_opclass",
	"qb_enum":                            "pg_enum",
	"qb_transform":                       "pg_transform",
	"qb_foreign_data_wrapper":            "pg_foreign_data_wrapper",
	"qb_user_mappings":                   "pg_user_mappings",
	"qb_ts_parser":                       "pg_ts_parser",
	"qb_ts_config":                       "pg_ts_config",
	"qb_ts_template":                     "pg_ts_template",
	"qb_ts_dict":                         "pg_ts_dict",
	"qb_opfamily":                        "pg_opfamily",
	"qb_operator":                        "pg_operator",
	"qb_aggregate":                       "pg_aggregate",
	"qb_cast":                            "pg_cast",
	"qb_get_viewdef":                     "pg_get_viewdef",
	"qb_constraint":                      "pg_constraint",
	"qb_get_constraintdef":               "pg_get_constraintdef",
	"qb_conversion":                      "pg_conversion",
	"qb_index":                           "pg_index",
	"qb_get_indexdef":                    "pg_get_indexdef",
	"qb_rewrite":                         "pg_rewrite",
	"qb_get_ruledef":                     "pg_get_ruledef",
	"qb_trigger":                         "pg_trigger",
	"qb_get_triggerdef":                  "pg_get_triggerdef",
	"qb_default_acl":                     "pg_default_acl",
	"qb_event_trigger":                   "pg_event_trigger",
	"qb_policy":                          "pg_policy",
	"qb_statistic_ext":                   "pg_statistic_ext",
	"qb_get_statisticsobjdef":            "pg_get_statisticsobjdef",
	"qb_partition":                       "pg_partition",
	"qb_get_partition_def":               "pg_get_partition_def",
	"qb_get_partition_template_def":      "pg_get_partition_template_def",
	"qb_tablespace_location":             "pg_tablespace_location",
	"qb_global":                          "pg_global",
	"qb_aoseg":                           "pg_aoseg",
	"qb_bitmapindex":                     "pg_bitmapindex",
	"qb_toast":                           "pg_toast",
	"qb_tablespace":                      "pg_tablespace",
	"qb_database_size":                   "pg_database_size",
	"qb_database":                        "pg_database",
	"qb_partition_rule":                  "pg_partition_rule",
	"qb_attribute_encoding":              "pg_attribute_encoding",
	"qb_resqueuecapability":              "pg_resqueuecapability",
	"qb_resgroupcapability":              "pg_resgroupcapability",
	"qb_type_encoding":                   "pg_type_encoding",
	"qb_type":                            "pg_type",
	"qb_amop":                            "pg_amop",
	"qb_ts_config_map":                   "pg_ts_config_map",
	"qb_amproc":                          "pg_amproc",
	"qb_lsn":                             "pg_lsn",
	"qb_default":                         "pg_default",
	"qb_filespace":                       "pg_filespace",
	"qb_filespace_entry":                 "pg_filespace_entry",
	"qb_system":                          "pg_system",
	"qb_":                                "pg_",
	"plpgsql_call_handler":               "plqbsql_call_handler",
	"plpgsql_validator":                  "plpgsql_validator",
}

func main2() {
	query := `SELECT pr1.oid AS partitionruleoid,
		pr1.parparentrule AS partitionparentruleoid,
		cl.oid AS parentrelationoid,
		quote_ident(n.nspname) AS parentschema,
		quote_ident(cl.relname) AS parentrelationname,
		pr1.parchildrelid AS relationoid,
		CASE WHEN pr1.parname = '' THEN '' ELSE quote_ident(pr1.parname) END AS partitionname,
		CASE WHEN pp.parkind <> 'r'::"char" OR pr1.parisdefault THEN 0
			ELSE qb_catalog.rank() OVER (PARTITION BY pp.oid, cl.relname, pp.parlevel, cl3.relname
				ORDER BY pr1.parisdefault, pr1.parruleord) END AS partitionrank,
		CASE WHEN e.reloid IS NOT NULL then 't' ELSE 'f' END AS isexternal
	FROM qb_namespace n, qb_namespace n2, qb_class cl
		LEFT JOIN qb_tablespace sp ON cl.reltablespace = sp.oid, qb_class cl2
		LEFT JOIN qb_tablespace sp3 ON cl2.reltablespace = sp3.oid, qb_partition pp, qb_partition_rule pr1
		LEFT JOIN qb_partition_rule pr2 ON pr1.parparentrule = pr2.oid
		LEFT JOIN qb_class cl3 ON pr2.parchildrelid = cl3.oid
		LEFT JOIN qb_exttable e ON e.reloid = pr1.parchildrelid
	WHERE pp.paristemplate = false
		AND pp.parrelid = cl.oid
		AND pr1.paroid = pp.oid
		AND cl2.oid = pr1.parchildrelid
		AND cl.relnamespace = n.oid
		AND cl2.relnamespace = n2.oid`

	if strings.Contains(query, "qb") {
		for qbKey, pgValue := range GlobalMap {
			query = strings.Replace(query, qbKey, pgValue, -1)
		}
	}
	fmt.Println(query)
	fmt.Println("----------------------")

	query2 := `qb_catalog qb_catalog1 qb_catalog_2`

	if strings.Contains(query2, "qb") {
		for k, pgValue := range GlobalMap {
			if strings.Contains(query2, k) {

				re := regexp.MustCompile(`\b` + k + `\b`)
				// 上述正则表达式匹配qb_tablespace，同时要求其前后没有其他字符
				query2 = re.ReplaceAllString(query2, pgValue)
			}
		}
	}
	fmt.Println(query2)
}

func main() {

	main3()
}

func InitializeVersion() {
	VersionString := " GaiaDB 12beta2 (GaiaDB-A Database 7.0.0-alpha.0+dev.16018.g6a8acd2b18 build dev) on aarch64-unknown-linux-gnu, compiled by gcc (GCC) \n7.3.0, 64-bit compiled on Mar 30 2023 17:34:16"
	versionStart := strings.Index(VersionString, "(QianBaseMPP Database ") + len("(QianBaseMPP Database ")
	versionEnd := strings.Index(VersionString, ")")
	VersionString = VersionString[versionStart:versionEnd]

	pattern := regexp.MustCompile(`\d+\.\d+\.\d+`)
	threeDigitVersion := pattern.FindStringSubmatch(VersionString)[0]
	println(threeDigitVersion)
	return
}

func main3() {
	query := "CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql HANDLER pg_catalog.plpgsql_call_handler VALIDATOR pg_catalog.plpgsql_validator;"

	for qbKey, pgValue := range GlobalMap {
		query = strings.Replace(query, qbKey, pgValue, -1)
	}
	fmt.Println(query)
}
